package com.example.saifly.inPageRecord;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.common.Util.BreathDataUtil;
import com.example.common.Util.FloatUtil;
import com.example.common.Util.TimeUtil;
import com.example.saifly.R;
import com.example.saifly.inPageRecord.RecordModel.BodyData;
import com.example.saifly.inPageRecord.RecordModel.BreathData;
import com.example.saifly.inPageRecord.RecordModel.EnvironmentData;
import com.example.saifly.inPageRecord.RecordModel.TotalScore;
import com.example.saifly.inPageRecord.score.ScoreBodyEnvironment;
import com.example.saifly.mainPage.record.RecordFragment;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.formatter.LineChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.view.LineChartView;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;


public class DisplayRecordActivity extends Activity {

    private LineChartView lineChart;
    private AVLoadingIndicatorView loadingView;
    private Date date = new Date();

    private float breathScore,environmentScore,bodyScore,questionScore,comployScore;

    private static String token;

    private SharedPreferences sharedPreferences;

    private String[] column={"pefr","leak","vte","rr","mv"};

    private List<TotalScore> chartDataList=new ArrayList<>();
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
    private ConstraintLayout clBreathCard,clBodyEnvironmentCard;
    private RelativeLayout loadingLayout;
    private LinearLayout llGood,llNormal,llBad;
    private CardView cvText;
    private TextView tvbody_detail,tvEnvironment_detail;
    private TextView tvBodyEnvironmentScore,tvTotalScore,tvCureScore,tvEnvironmentScore,tvBodyScore,tvBreathScore,tvNickname,tvTime;
    private boolean isBreathDone=false;
    private boolean isBodyDone=false;
    private boolean isEnvironmentDone=false;
    private boolean isQuestionDone=false;
    private boolean isComployDone=false;
    private String uid;
    private BreathData singleBreath=new BreathData();
    private List<BreathData> dataList=new ArrayList<>();
    private ScoreBodyEnvironment scoreBodyEnvironment=new ScoreBodyEnvironment();

    private float vte;//潮气量
    private float rr;//呼吸频率
    private float leak;//漏气量
    private double pefr=0;//峰流速



    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_display_record;
    }

    @Override
    protected void init() {
        Log.d("displayy", "init: "+column);
        super.init();
        lineChart=findViewById(R.id.display_chart);
        clBreathCard=findViewById(R.id.display_breath_card);
        clBodyEnvironmentCard=findViewById(R.id.display_body_card);
        loadingView=findViewById(R.id.display_avi);
        loadingLayout=findViewById(R.id.display_loading_view);
        tvTotalScore=findViewById(R.id.display_total_score);
        tvCureScore=findViewById(R.id.display_cure_score);
        tvEnvironmentScore=findViewById(R.id.display_environment_score);
        tvbody_detail=findViewById(R.id.body_detail);
        tvEnvironment_detail=findViewById(R.id.environment_detail);
        tvBodyScore=findViewById(R.id.display_body_score);
        tvBreathScore=findViewById(R.id.display_breath_score);
        tvNickname=findViewById(R.id.display_nickname);
        tvTime=findViewById(R.id.display_time);
        tvBodyEnvironmentScore=findViewById(R.id.display_body_environment_score);
        llGood=findViewById(R.id.display_feel_good);
        llNormal=findViewById(R.id.display_feel_normal);
        llBad=findViewById(R.id.display_feel_bad);
        cvText=findViewById(R.id.display_feel_text);


        //初始化全局变量，稍后用于取个人信息
        sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        uid=sharedPreferences.getString("uid","unexisted");


        //加载ui开始
        loadingStart();

        //获取数据
        getData();

        //设置点击事件
        initClick();



    }

    private void getData(){
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");// HH:mm:ss
        sharedPreferences.edit().putString("time",simpleDateFormat.format(date)).apply();
        tvTime.setText(simpleDateFormat.format(date));
        //提醒frament_record中更新数据
        RecordFragment.reloadData();
        //获取用户昵称
        tvNickname.setText(sharedPreferences.getString("nickname","默认用户"));

        //登陆后获取呼吸机数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                login();
            }
        }).start();

        //获取环境数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                getEnvironmentData();
            }
        }).start();

        //获取身体数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                getBodyData();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                getQuesData();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                getComployData();
            }
        }).start();

        //监听数据是否获取完成，完成后开始打分
        new Thread(new Runnable() {
            @Override
            public void run() {
                calculate();
            }
        }).start();

    }

    private interface ApiGetDisplayData{
        //登陆
        @Headers({"Content-Type:application/json"})
        @POST("/v1/user/login")
        Call<ResponseBody> GetToken(@Body JSONObject jsonObject);

        //获取历史得分
        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getTop10TotalScore")
        Call<ResponseBody> GetHistory(@Body JSONObject jsonObject);

        //获取呼吸机数据
        @Headers( {"Content-Type:application/json"})
        @POST("/v1/Data/searchData.json")
        Call<ResponseBody> GetBreathData(@Body JSONObject jsonObject, @Header("token") String value);

        //获取环境得分
        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getEstimateEnvironmentData")
        Call<ResponseBody> GetEnvironmentData(@Body JSONObject jsonObject);

        //获取身体得分
        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getEstimateBodyData")
        Call<ResponseBody> GetBodyData(@Body JSONObject jsonObject);

        //获取问卷情况
        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getDailyQuestionnaire")
        Call<ResponseBody> GetQuestion(@Body JSONObject jsonObject);

        //依从性情况
        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getDailyPlanFinish")
        Call<ResponseBody> GetPlanFinish(@Body JSONObject jsonObject);

        //上传得分
        @Headers({"Content-Type:application/json"})
        @POST("/estimate/submitTotalScore")
        Call<ResponseBody> SubmitTotalScore(@Body JSONObject jsonObject);
    }

    private void getHistoryScore(){
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",uid);


        Call<ResponseBody> call=apiGetDisplayData.GetHistory(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    Log.d("gethissss", "getHistoryScore: "+result.toString());
                    chartDataList=JSON.parseArray(result.getString("result"),TotalScore.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(chartDataList.size()>1){
                                getAxisPoints();//获取坐标点
                                initLineChart();//初始化
                            }
                            else{
                                lineChart.setVisibility(View.GONE);
                            }
                        }
                    });
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DisplayRecordActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DisplayRecordActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }



    private void login(){
        OkHttpClient client=new OkHttpClient.Builder().build();

        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://39.107.224.48:80")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("loginCode","xuehai");
        jsonObject.put("password","123456");

        Call<ResponseBody> call=apiGetDisplayData.GetToken(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getString("code").equals("200")){
                    //==200登陆成功
                    token = result.getJSONObject("data").getString("token");
                    //成功调取呼吸机数据
                    Log.d("displayy", "login: success");
                    dealWithBreath();
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DisplayRecordActivity.this,"连接呼吸机失败",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DisplayRecordActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    private void dealWithBreath(){
        BreathDataUtil breathDataUtil=new BreathDataUtil();
        while(dataList.size()<10) {
            String endTime = breathDataUtil.GetDate();
            breathDataUtil.ReduceADay();
            String startTime = breathDataUtil.GetDate();
            while (!getBreathData(startTime + " 00:00:00", endTime + " 00:00:00")) {
                endTime = startTime;
                breathDataUtil.ReduceADay();
                startTime = breathDataUtil.GetDate();
            }
            for (int i = 0; i <= 6; i++) {
                int j = i + 1;
                getBreathData(startTime + " " + i + ":00:00", startTime + " "+ j + ":00:00");
            }
            for (int i = 18; i < 23; i++) {
                int j = i + 1;
                getBreathData(startTime + " " + i + ":00:00", startTime + " " + j + ":00:00");
            }
            getBreathData(startTime + " 23:00:00", startTime + " 23:59:59");
        }
        breathScore=getBreathScrore();
        isBreathDone=true;
    }

    private boolean getBreathData(String startTime,String endTime){
        OkHttpClient client=new OkHttpClient.Builder().build();

        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://39.107.224.48:80")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("deviceNo","07F070122");
        jsonObject.put("startedTime",startTime);
        jsonObject.put("endedTime",endTime);
        jsonObject.put("dataType","ri_rl_rh_rc");
        jsonObject.put("colunm",column);
        jsonObject.put("pageSize",0);
        Log.d("displayy", "getBreathData: "+jsonObject);

        Call<ResponseBody> call=apiGetDisplayData.GetBreathData(jsonObject,token);
        final Response<ResponseBody> response;
        try {
            response=call.execute();
            String responseString=response.body().string();
            JSONObject resultObject=JSON.parseObject(responseString);
            List<BreathData> breathDataList =new ArrayList<>();
                   breathDataList = JSONObject.parseArray(resultObject.getString("data"), BreathData.class);
            if(breathDataList.size()!=0){
                dataList.add(breathDataList.get(0));
                return true;
            }

//            Log.d("displayy", "获取到的类列表为"+breathDataList.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;

    }

    private void getEnvironmentData(){
        RetrofitHelper helper=new RetrofitHelper();
        Retrofit retrofit=helper.getRetrofit();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",uid);
        Log.d("patientPhone", "patientPhone: "+uid);
        Call<ResponseBody> call=apiGetDisplayData.GetEnvironmentData(jsonObject);
        Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    EnvironmentData environmentData=JSON.parseObject(result.getString("result"), EnvironmentData.class);
                    Log.d("environmentData", "getEnvironmentData: "+environmentData.toString());
                    scoreBodyEnvironment.setEnvironmentData(environmentData);
                    environmentScore=scoreBodyEnvironment.environmentScore();
                    Log.d("questionScore", "getenvironData: "+environmentScore);
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DisplayRecordActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DisplayRecordActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
        isEnvironmentDone=true;
    }

    private void getBodyData(){
        RetrofitHelper helper=new RetrofitHelper();
        Retrofit retrofit=helper.getRetrofit();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",uid);

        Call<ResponseBody> call=apiGetDisplayData.GetBodyData(jsonObject);
        Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    BodyData bodyData =JSON.parseObject(result.getString("result"),BodyData.class);
                    Log.d("bodyData", "getBodyData: "+bodyData.toString());
                    scoreBodyEnvironment.setBodyData(bodyData);
                    bodyScore=scoreBodyEnvironment.bodyScore();
                    Log.d("questionScore", "getbodyData: "+bodyScore);
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DisplayRecordActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DisplayRecordActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
        isBodyDone=true;
    }

    private void getQuesData(){

        RetrofitHelper helper=new RetrofitHelper();
        Retrofit retrofit=helper.getRetrofit();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",uid);

        Call<ResponseBody> call=apiGetDisplayData.GetQuestion(jsonObject);
        Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                Log.d("response","asdfsadf"+result.toString());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){

                    if(result.getString("result").length()==1)
                    {
                        questionScore=0;
                        Log.d("popo", "getQuesData: "+questionScore);
                    }
                    else
                    {
                        questionScore = result.getJSONObject("result").getFloat("totalscore");
                        questionScore*=2.5;
                        Log.d("questionScore", "getQuesData: "+questionScore);
                    }
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DisplayRecordActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DisplayRecordActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
        isQuestionDone=true;
    }

    private void getComployData(){
        RetrofitHelper helper=new RetrofitHelper();
        Retrofit retrofit=helper.getRetrofit();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        Long dateLong=new Date().getTime();

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",uid);
        jsonObject.put("date",dateLong);

        Call<ResponseBody> call=apiGetDisplayData.GetPlanFinish(jsonObject);
        Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    Log.d("result", "getComployData: "+result.toString());
                    comployScore=result.getFloat("result")*100;
                    Log.d("questionScore", "getcomplyData: "+comployScore);
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DisplayRecordActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DisplayRecordActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
        isComployDone=true;
    }

    private void calculate(){
        while(true){
            Log.d("hahahhh", "calculate: "+isBreathDone+isBodyDone+isQuestionDone+isEnvironmentDone+isComployDone);
            if(isBreathDone&&isBodyDone&&isQuestionDone&&isEnvironmentDone&&isComployDone){
                Log.d("hahahhh", "calculate: "+isBreathDone+isBodyDone+isQuestionDone+isEnvironmentDone+isComployDone);
                break;
            }
        }


        TotalScore totalScore=new TotalScore();
        totalScore.setBodydateScore(bodyScore);
        totalScore.setDailyplanScore(comployScore);
        totalScore.setDailyQuestionScore(questionScore);
        totalScore.setEnvironmentScore(environmentScore);
        totalScore.setVentilatorScore(breathScore);
        totalScore.setDate(date);
        totalScore.setPatientPhone(uid);
        totalScore.calculateTotalScore();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UpdateUIScore(totalScore);
            }
        });

        Log.d("totalll", "calculate: "+totalScore.toString());

        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("totalScore",JSON.toJSONString(totalScore));

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        Call<ResponseBody> call=apiGetDisplayData.SubmitTotalScore(jsonObject);
        //加载ui结束
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingEnd();
            }
        });
        Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                Log.d("uploaddddd", "calculate: "+result.toString());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    getHistoryScore();
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DisplayRecordActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DisplayRecordActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }


    }

    private void UpdateUIScore(TotalScore totalScore) {
        tvTotalScore.setText(FloatUtil.holdDecimal(totalScore.getTotalScore(),2));
        tvEnvironmentScore.setText(FloatUtil.holdDecimal(totalScore.getEnvironmentScore(),2));
        tvBodyScore.setText(FloatUtil.holdDecimal(totalScore.getBodydateScore(),2));
        tvBreathScore.setText(FloatUtil.holdDecimal(totalScore.getVentilatorScore(),2));
        Float bodyEnvironmentScore = totalScore.getEnvironmentScore()+ totalScore.getBodydateScore();
        bodyEnvironmentScore/=2;
        tvBodyEnvironmentScore.setText(FloatUtil.holdDecimal(bodyEnvironmentScore,2));
        tvCureScore.setText(FloatUtil.holdDecimal(totalScore.getDailyplanScore(),2));
    }

    private void loadingStart(){
        loadingLayout.setOnClickListener(null);
        loadingView.show();
    }

    private void loadingEnd(){
        loadingView.hide();
        loadingLayout.setVisibility(View.GONE);
    }

    private void initClick() {
        tvbody_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DisplayRecordActivity.this,BodyDataActivity.class));
            }
        });

        tvEnvironment_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DisplayRecordActivity.this,EnvironmentActivity.class));
            }
        });
        clBreathCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DisplayRecordActivity.this,BreathActivity.class)
                        .putExtra("dataList", (Serializable) dataList)
                        .putExtra("breathScore",FloatUtil.holdDecimal(breathScore,2)));
            }
        });
        llGood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cvText.setVisibility(View.INVISIBLE);
                Toast.makeText(DisplayRecordActivity.this,"已收到您的评价",Toast.LENGTH_SHORT).show();
            }
        });
        llNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cvText.setVisibility(View.INVISIBLE);
                Toast.makeText(DisplayRecordActivity.this,"已收到您的评价",Toast.LENGTH_SHORT).show();
            }
        });
        llBad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cvText.setVisibility(View.INVISIBLE);
                Toast.makeText(DisplayRecordActivity.this,"已收到您的评价",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initLineChart() {


        LineChartValueFormatter chartValueFormatter = new SimpleLineChartValueFormatter(2);

        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(true);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
        line.setFormatter(chartValueFormatter);//显示小数点
//      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //X轴的设置
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.rgb(17,150,238));  //设置字体颜色
        //axisX.setName("date");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(5); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX);
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        //Y轴的设置
        Axis axisY = new Axis();  //Y轴
        axisY.setName("");//y轴标注
        axisY.setTextSize(8);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边

        //动态图表
        lineChart.setInteractive(false);
        lineChart.setZoomType(ZoomType.HORIZONTAL);
        lineChart.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        lineChart.setLineChartData(data);
        lineChart.setVisibility(View.VISIBLE);

    }

    private void getAxisPoints() {
        int size=chartDataList.size();
            for (int i = 0; i < chartDataList.size(); i++) {
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");// HH:mm:ss
//                Log.d("jjjjj", "getAxisPoints: "+chartDataList.get(i).getTotalScore()+" "+simpleDateFormat.format(chartDataList.get(i).getDate()));
//                mPointValues.add(new PointValue(i, chartDataList.get(i).getTotalScore()));
//                mAxisXValues.add(new AxisValue(i).setLabel(simpleDateFormat.format(chartDataList.get(i).getDate())));
                mPointValues.add(new PointValue(size-i-1, chartDataList.get(i).getTotalScore()));
                mAxisXValues.add(new AxisValue(size-i-1).setLabel(TimeUtil.Date2StringMD(chartDataList.get(i).getDate())));
            }
        Log.d("displayFinal", "getAxisPoints: "+chartDataList.toString());
    }

    private float getBreathScrore()
    {
        float  score=0;
        for(int i=0;i<dataList.size();i++){
            vte+=dataList.get(i).getVte();
            rr+=dataList.get(i).getRr();
            leak+=dataList.get(i).getLeak();
            if(dataList.get(i).getPefr()>pefr){
                pefr=dataList.get(i).getPefr();
            }
        }
        int i=dataList.size();
        vte=vte/i;
        vte=vte/60;
        rr=rr/i;
        leak=leak/i;

        if(rr>=15&&rr<=20)
        {
            score += 100*0.4;
        }
        else if(rr>20&&rr<30)
        {
            score+=(100-(rr-20)*10)*0.4;
        }
        else if(rr<15&&rr>=5)
        {
            score+=(100-(15-rr)*10)*0.4;
        }

        if (vte>=8&&vte<=15)
        {
            score+=(100)*0.4;
        }
        else if (vte<8&&vte>=3)
        {
            score+=(100-(8-vte)*20)*0.4;
        }
        else if (vte>15&&vte<=20)
        {
            score+=(100-(vte-15)*20)*0.4;
        }

        if(leak>100)
        {
            score+=90*0.2;
        }
        else if(leak>0)
        {
            score+=100*0.2;
        }
        return score;
    }

    private void initHistory(){


    }



}
